//
//  FacebookConnectOperation.m
//  volleyMe
//
//  Created by Gabi Gavrilut on 2/21/12.
//  Copyright (c) 2012 Aelius International. All rights reserved.
//

#import "FacebookConnectOperation.h"
#import "AppDelegate.h"
#import "HomeViewController.h"
#import "User.h"
@implementation NSDictionary (Extension)

- (id)newObjectForKey:(id)aKey
{
    id rez = [self objectForKey:aKey];
    
    return ([rez isKindOfClass:[NSNull class]] ? nil : rez);
}
@end
#import "CreateAccountMoreController.h"


@implementation FacebookConnectOperation

@synthesize facebook, viewController;

- (id)initWithFacebook: (Facebook *) my_facebook 
{
    self.facebook = my_facebook;
    return [super init];
}

- (void) readFacebookData: (id)data {
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   @"SELECT uid, name, email, birthday, hometown_location, first_name, last_name, middle_name, username,sex FROM user WHERE uid=me()", @"query",
                                   nil];
    [facebook requestWithMethodName:@"fql.query"
                                     andParams:params
                                 andHttpMethod:@"POST"
                                   andDelegate:(id)self];

}

- (void)request:(FBRequest *)request didLoad:(id)result 
{
    [[AppDelegate shareDelegate] hideLoadingView];
    
    NSArray *data_array = result;
    NSDictionary *data = [data_array objectAtIndex:0];  
    NSLog(@"%@",data);
    
    NSString* fb_id =  [[data objectForKey:@"uid"] stringValue] ;
    NSString* email = [data objectForKey:@"email"] ;
    NSString* name = [data objectForKey:@"name"];
    NSString* gender =[data objectForKey:@"sex"] ;
    NSString* username = [data objectForKey:@"username"]; 
    NSString* birthday = [data objectForKey:@"birthday"];
    
    gender = [gender isEqualToString:@"Male"] ? @"1" : @"0";
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMMM dd, yyyy"];    
    NSDate *birthdayDate = [formatter dateFromString:birthday]; 
    
    formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString* dob = [formatter stringFromDate:birthdayDate];
    [formatter release];
    
    NSString* loginData = [NSString stringWithFormat:@"name=%@&dob=%@&gender=%@&email=%@&fb_id=%@&fb_username=%@",name,dob,gender,email,fb_id,username];
    NSLog(@"LoginData: %@",loginData);
    
    MBProgressHUD *progress = [JGoUtility showProgressInView:self.viewController.view 
                                                      target:self 
                                                       title:@"Logging in..." 
                                                    selector:@selector(delayLogin:)];
    progress.userInfo = data;      
}

- (void) prepareDataForRequest: (id)result 
{
    
}

- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
    NSLog(@"Err message: %@", [[error userInfo] objectForKey:@"error_msg"]);
    NSLog(@"Err code: %d", [error code]);
        
}

- (void)dealloc 
{
    [facebook release];
    [viewController release];
    [super dealloc];
}

- (void)delayLogin:(MBProgressHUD*)progress
{
    NSDictionary *data = (id)progress.userInfo;      
    NSString* fb_id =  [[data objectForKey:@"uid"] stringValue] ;
    NSString* email = [data objectForKey:@"email"] ;
    NSString* name = [data objectForKey:@"name"];
    
    NSString* username = [data objectForKey:@"username"]; 
    NSString* birthday = [data objectForKey:@"birthday"];
    NSError *error = nil;
    
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"MMMM dd, yyyy"];    
    NSDate *birthdayDate = [formatter dateFromString:birthday]; 
    
    formatter = [[[NSDateFormatter alloc]init] autorelease];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString* dob = [formatter stringFromDate:birthdayDate];
    
    NSString* sex =[data objectForKey:@"sex"] ;
    NSString* gender;
    if ([sex isEqualToString:@"male"]) {
        gender = @"1";
    }else {
        gender = @"0";
    }
    NSDictionary *object = [JGoAPI loginWithFacebookId:fb_id 
                                                fb_name:name 
                                                 fb_dob:dob 
                                                 gender:gender 
                                               fb_email:email 
                                            fb_username:username 
                                                  error:&error];
    
    if (error) {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    else {
        NSString *modules = [object objectForKey:@"modules"];
        NSString *dobString = [object objectForKey:@"dob"];  
        NSDate *dob = [JGoUtility dateFromString1:dobString];
        
        [object setValue:dob forKey:@"dob"];
        
        if ([modules length]) {
            NSArray *arrayModule = [modules componentsSeparatedByString:@";"];
            [object setValue:arrayModule forKey:@"modules"];
        }
        else {
            [object setValue:nil forKey:@"modules"];
        }    
        
        [JGoUtility copySharedCreateAccount:object];
        NSLog(@"sharedCreateAccount: %@",[JGoUtility sharedCreateAccount]);
        NSString *uni = [[JGoUtility sharedCreateAccount] newObjectForKey:@"university"];
        NSString *course = [[JGoUtility sharedCreateAccount] newObjectForKey:@"course"];
        NSArray *mdl = [[JGoUtility sharedCreateAccount] newObjectForKey:@"modules"];
        NSString *class_year = [[JGoUtility sharedCreateAccount] newObjectForKey:@"c_year"];

        if (uni == nil || [uni isEqualToString:@""] || course == nil || [course isEqualToString:@""] ||
            mdl == nil || [mdl count] == 0 || class_year == nil || [class_year isEqualToString:@""]) {
            CreateAccountMoreController * camVC = [[[CreateAccountMoreController alloc] initWithNibName:@"CreateAccountMoreController"
                                                                                                 bundle:nil] autorelease];
            UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:camVC];
            navController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
            [self.viewController presentModalViewController:navController animated:YES];

        }else {
            HomeViewController *homeView = [[[HomeViewController alloc]initWithNibName:@"HomeViewController" bundle:nil] autorelease];
            UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:homeView];
            navController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
            [self.viewController presentModalViewController:navController animated:YES];  
            

        }
        
                
        
        
            }
    
    [progress hide:YES];
}

@end
